import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

/**
 * @description: pinia 没有模块和mutations,配合vue3的使用
 * npm install pinia
 * store
  * 创建：const useXXXStore = defineStore('XXX', { ... }) //可以创建任意多个store
  * 注册：app.use(createPinia()) //import { createPinia } from 'pinia'
  * 使用：setup中
    * const store = useXXXStore()
    * const {count, name, age} = storeToRefs(counterStore)//解构state,getters
    * const {increment} = counterStore;//解构actions
    * doubleValue: computed(() => counterStore.double)//getters直接使用的方法
 * state
    * 重置 store.$reset()
    * setup中可以直接读写（双向绑定）
    * store.$patch(state=> {}) // 修改多个state
    * const unsubscribe = store.$subscribe(fn) //监听state的变化执行回调，返回的是取消订阅函数
 * getters
 * actions 可以直接store.actionFn访问
    * 订阅监听 counterStore.$onAction(({after, onError})=> {})
 * 所有的订阅都是绑定组件的，组件卸载之后订阅也会删除，不想删除的话，一般有第二个参数可以解绑
 */



/**
 * option store
 */
export const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 1,
      name: 'sunyucui',
      age: 26,
      msg: "msg"
    }
  },
  getters: {
    double: (state) => state.count * 2
  },
  actions: {
    increment() {
      return new Promise((res,rej)=> {
        setTimeout(()=> {
          this.count++
          res('increment succeed')
          // rej('increment failed')
        }, 3000)
      })
    }
  }
})
/**
 * setup Store
 */
// export const useCounterStore = defineStore('counter', () => {
//   const count = ref(0)
//   const doubleCount = computed(() => count.value * 2)
//   function increment() {
//     count.value++
//   }

//   return { count, doubleCount, increment }
// })
